package com.zuul.provider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

/**
 *	 容错与回退
 * @author whxn520 2021年10月10日下午8:04:47
 */
@Component
public class DefaultFallbackProvider implements FallbackProvider{

	private final Logger logger = LoggerFactory.getLogger(DefaultFallbackProvider.class);
	
	@Override
	public String getRoute() {
		// 表明是为哪个微服务提供回退，*表示为所有微服务提供回退，使用serviceId的话，则为单个微服务
		return "*";
	}

	@Override
    public ClientHttpResponse fallbackResponse(Throwable cause) {
        if (cause != null && cause.getCause() != null) {
            String reason = cause.getCause().getMessage();
            logger.info("Excption {}",reason);
        }
        return fallbackResponse();
    }

	@Override
	public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            /**
             * 	网关向api服务请求是失败了，但是消费者客户端向网关发起的请求是OK的，
             * 	不应该把api的404,500等问题抛给客户端
             * 	网关和api服务集群对于客户端来说是黑盒子
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                // 当fallback时返回给调用者的状态码
                return HttpStatus.OK;
            }
            @Override
            public int getRawStatusCode() throws IOException {
            	// 返回数字类型的状态码
                return HttpStatus.OK.value();
            }
            @Override
            public String getStatusText() throws IOException {
                // 状态码的文本形式
            	return HttpStatus.OK.getReasonPhrase();
            }
            @Override
            public void close() {
 
            }
 
            @Override
            public InputStream getBody() throws IOException {
                // 响应体
                Map<String,String> result = Maps.newHashMap();
                result.put("code", String.valueOf(HttpStatus.SERVICE_UNAVAILABLE));
	            result.put("msg", "服务不可用，请稍后重试！");
                return new ByteArrayInputStream(JSON.toJSONString(result).getBytes("UTF-8"));
            }
 
            @Override
            public HttpHeaders getHeaders() {
                // 设定headers
                HttpHeaders headers = new HttpHeaders();
                // 和body中的内容编码一致，否则容易乱码
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
	}

}
